package optional.code;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Description: Optional-JDK9新增API使用示例
 *
 * @author code-worker
 * @date 2021/08/28 10:48
 */
public class PracticeJdk9 {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "PracticeJdk9{" +
                "name='" + name + '\'' +
                '}';
    }

    /**
     * task: 示例: or
     *       区别于orElse和orElseGet，该方法可以继续返回optional对象
     * @date 2021/8/28 14:56
     */
    public void orUsage(){
        String methodName = "orUsage: ";
        PracticeJdk9 jdk9 = null;
        jdk9 = Optional.ofNullable(jdk9).orElse(new PracticeJdk9());
        System.out.println(methodName + jdk9);
        jdk9 = null;
        jdk9 = Optional.ofNullable(jdk9).orElseGet(PracticeJdk9::new);
        System.out.println(methodName + jdk9);
        jdk9 = null;
        jdk9 = Optional.ofNullable(jdk9).or(()-> Optional.of(new PracticeJdk9())).get();
        System.out.println(methodName + jdk9);
    }

    /**
     * task: ifPresentOrElse示例
     * @date 2021/8/28 15:07
     */
    public void ifPresentOrElse(){
        String methodName = "ifPresentOrElse: ";
        PracticeJdk9 jdk9 = new PracticeJdk9();
        Optional.ofNullable(jdk9.getName()).ifPresentOrElse(
                //如果存在值，输出相应值
                v-> System.out.println(methodName + "name: "+ v),
                //如果不存在值，提示没有赋值
                () -> System.out.println(methodName + "name没有赋值！")
        );
    }

    /**
     * task: scream示例
     * @date 2021/8/28 15:19
     */
    public void scream(){
        String methodName = "scream: ";
        List<String> list = new ArrayList<>(8);
        list.add("hello");
        list.add("world");
        Optional.of(list).stream().filter(v -> !v.isEmpty()).forEach((v)-> System.out.println(methodName + v));
    }

    public static void main(String[] args) {
        PracticeJdk9 demo = new PracticeJdk9();
        demo.orUsage();
        demo.ifPresentOrElse();
        demo.scream();
    }
}
